package com.foftact.etfrank.controller;

import com.foftact.etfrank.ETFRank;
import com.foftact.etfrank.service.ETFRankService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ETF排行控制器
 */
@Controller
@RequestMapping("/etfrank")
public class ETFRankController {

    private static final Logger logger = LoggerFactory.getLogger(ETFRankController.class);
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private ETFRankService etfRankService;

    /**
     * 跳转到ETF排行数据列表页面
     */
    @GetMapping("/list")
    public String listPage(Model model) {
        // 设置默认日期为今天
        model.addAttribute("defaultDate", DATE_FORMAT.format(new Date()));
        return "etfrank/list";
    }

    /**
     * 异步获取ETF排行数据列表
     */
    @GetMapping("/dataList")
    @ResponseBody
    public Map<String, Object> getDataList(@RequestParam(required = false) String date,
                                         @RequestParam(required = false) String orderByField,
                                         @RequestParam(required = false) String orderByDirection,
                                         @RequestParam(required = false, defaultValue = "50") Integer limit) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("获取ETF排行数据列表，日期:{}, 排序字段:{}, 排序方向:{}, 限制数量:{}", 
                       date, orderByField, orderByDirection, limit);
            
            Date navDate;
            if (date != null && !date.isEmpty()) {
                navDate = DATE_FORMAT.parse(date);
            } else {
                navDate = new Date();
            }
            
            if (orderByField == null || orderByField.isEmpty()) {
                orderByField = "weekly_growth_rate";
            }
            
            if (orderByDirection == null || orderByDirection.isEmpty()) {
                orderByDirection = "desc";
            }
            
            List<ETFRank> etfRankList = etfRankService.getETFRankByGrowthRate(
                    orderByField, orderByDirection, limit);
            
            result.put("success", true);
            result.put("data", etfRankList);
        } catch (Exception e) {
            logger.error("获取ETF排行数据列表失败", e);
            result.put("success", false);
            result.put("message", "获取数据失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 手动触发数据抓取
     */
    @GetMapping("/fetchData")
    @ResponseBody
    public Map<String, Object> fetchData() {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("手动触发ETF排行数据抓取");
            int count = etfRankService.fetchAndSaveETFRankData();
            result.put("success", true);
            result.put("message", "数据抓取成功，新增/更新数据：" + count + " 条");
            result.put("count", count);
        } catch (Exception e) {
            logger.error("手动触发数据抓取失败", e);
            result.put("success", false);
            result.put("message", "数据抓取失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据基金代码和日期获取ETF排行详情
     */
    @GetMapping("/detail")
    @ResponseBody
    public Map<String, Object> getDetail(@RequestParam String fundCode,
                                        @RequestParam String date) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("获取ETF排行详情，基金代码:{}, 日期:{}", fundCode, date);
            Date navDate = DATE_FORMAT.parse(date);
            ETFRank etfRank = etfRankService.getETFRankByCodeAndDate(fundCode, navDate);
            
            if (etfRank != null) {
                result.put("success", true);
                result.put("data", etfRank);
            } else {
                result.put("success", false);
                result.put("message", "未找到ETF排行数据");
            }
        } catch (Exception e) {
            logger.error("获取ETF排行详情失败，基金代码:{}, 日期:{}", fundCode, date, e);
            result.put("success", false);
            result.put("message", "获取详情失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 跳转到ETF排行数据统计页面
     */
    @GetMapping("/statistics")
    public String statisticsPage(Model model) {
        try {
            // 获取最近7天的数据作为统计基础
            List<ETFRank> recentData = etfRankService.getRecentETFRank(7);
            model.addAttribute("totalCount", recentData.size());
            
            // 获取最近一次数据的日期
            if (!recentData.isEmpty()) {
                model.addAttribute("lastUpdateDate", DATE_FORMAT.format(recentData.get(0).getNavDate()));
            }
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            model.addAttribute("totalCount", 0);
        }
        return "etfrank/statistics";
    }

    /**
     * 清理指定日期之前的数据
     */
    @PostMapping("/cleanData")
    @ResponseBody
    public Map<String, Object> cleanData(@RequestParam String beforeDate) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("清理日期{}之前的ETF排行数据", beforeDate);
            Date date = DATE_FORMAT.parse(beforeDate);
            int count = etfRankService.cleanOldETFRankData(date);
            
            result.put("success", true);
            result.put("message", "数据清理成功，删除" + count + "条记录");
            result.put("count", count);
        } catch (Exception e) {
            logger.error("清理数据失败", e);
            result.put("success", false);
            result.put("message", "数据清理失败：" + e.getMessage());
        }
        return result;
    }
}